<?php
namespace app\api\controller\kuyou\applet;
use think\Db;
class GoodsPurchaseSummarys extends Common
{
    public function index()
    {
        if ($this->request->isPost()) {
            $where = [];
            $code = $this->request->post('purchase_code');
            if(!empty($code)){
                $where['i.purchase_code'] = ['like','%'.$code.'%'];
            }
            $purchase_time = $this->request->post('purchase_time');
            if(!empty($purchase_time)){
                $str = explode('~',$purchase_time);
                if(isset($str[0]) && isset($str[1])){
                    $where['i.purchase_time'] = ["BETWEEN", [strtotime($str[0]),strtotime($str[1])]];
                }
            }
            $supplyer_code = $this->request->post('supplyer_code');
            if(!empty($supplyer_code)){
                $where['i.supplyer_code'] = $supplyer_code;
            }
            $goods_code = $this->request->post('goods_code');
            if(!empty($goods_code)){
                $where['i.goods_code'] = $goods_code;
            }
            $keyword = $this->request->post('keyword');
            if(!empty($keyword)){
                $where['i.supplyer_code|i.goods_code'] = $keyword;
            }

            $field = empty(input('field'))?'supplyer_code':trim(input('field'));
            $order = empty(input('sort'))?'DESC':trim(input('sort'));

            $sup = Db::name('kuyou_suppliers')->alias('sp')
                ->join('kuyou_supplyertype gt','sp.supplyertype_id=gt.id')
                ->field('sp.supplyer_code,sp.supplyer_name,gt.supplier_type_name')
                ->select();

            $listarr = [];
            foreach ($sup as $sup_k=>$sup_v){
                $list = [];
                $lists = Db::name('kuyou_goods_purchase_summary')->alias('i')
                    ->join('kuyou_goods g','g.goods_code=i.goods_code')
                    ->join('kuyou_stores s','s.id=i.stores_id')
                    ->join('kuyou_unit u','u.id=i.goods_unit')
                    ->where($where)
                    ->where(['i.supplyer_code'=>$sup_v['supplyer_code']])
                    ->order(['i.'.$field=>$order])
                    ->group('i.goods_code,i.stores_id')
                    ->field('sum(i.tax_money) as tax_money,sum(i.money_tax_price) as money_tax_price,i.goods_code,i.stores_id,sum(i.basic_nmber) as basic_nmber,sum(number) as i_number,unit_price,sum(all_money) as all_money,i.default_unit,i.goods_unit,i.purchase_money,
                g.goods_code,g.goods_name,g.goods_specification_id as goods_spec,g.unit_id,g.more_unit,g.id as goods_id,
                s.name as s_name,u.name as u_name')
                    ->select();

                if(!empty($lists)){
                    foreach ($lists as $lists_k=>$lists_v){
                        $lists_v['i_number'] = $lists_v['basic_nmber'];

                        $lists_v['unit_conversion'] = '';
                        if($lists_v['more_unit']==1){
                            $goodsUnit = (new \app\api\model\kuyou\applet\Goods())->getGoodsUnit($lists_v['goods_id']);
                            $unit_data = isset($goodsUnit['unit_data'])?$goodsUnit['unit_data']:[];
                            if(!empty($unit_data)){
                                $conversion = (new Commons())->getConversion($lists_v['i_number'],$unit_data);
                                if(isset($conversion['basic_nmber']) && isset($conversion['unit_conversion'])){
                                    $lists_v['basic_nmber'] = $conversion['basic_nmber'];
                                    $lists_v['unit_conversion'] = $conversion['unit_conversion'];
                                }else{
                                    $lists_v['basic_nmber'] = '';
                                    $lists_v['unit_conversion'] = '';
                                }
                            }
                        }

                        if(!empty($list)){
                            foreach ($list as $list_k=>$list_v){
                                if($list_v['goods_code']==$lists_v['goods_code'] && $list_v['stores_id']==$lists_v['stores_id']){
                                    $list[$list_k]['i_number'] += $lists_v['i_number'];
                                    $list[$list_k]['all_money'] += $lists_v['all_money'];
                                    $list[$list_k]['purchase_money'] += $lists_v['purchase_money'];
                                    $list[$list_k]['unit_price'] = round(($list[$list_k]['all_money']/$list[$list_k]['i_number']),2);
                                    $status = true;
                                }
                            }
                        }
                        if(!isset($status)){
                            $unit_name = Db::name('kuyou_unit')->where(['id'=>$lists_v['default_unit']])->value('name');
                            $lists_v['u_name'] = $unit_name;
                            $list[] = $lists_v;
                        }
                    }
                }
                foreach ($list as $list_k=>$list_v){
                    $list_v['all_money'] = round($list_v['all_money'],2);
                    if($list_v['i_number']!=0){
                        $list_v['unit_price'] = round($list_v['all_money']/$list_v['i_number'],2);
                    }else{
                        $list_v['unit_price'] = 0;
                    }
                    $list_v['tax_money'] = round($list_v['tax_money'],2);
                    $list_v['money_tax_price'] = round($list_v['money_tax_price'],2);

                    $list_v[$field] = $sup_v['supplyer_code'];
                    $list_v['supplyer_name'] = $sup_v['supplyer_name'];
                    $list_v['supplier_type_name'] = $sup_v['supplier_type_name'];
                    $list_v['s_type'] = 1;
                    $listarr[] = $list_v;
                }
                $sup[$sup_k]['list'] = $list;
            }

            //获取设置
            $set= \think\Db::name('kuyou_sets')->field('type,name,value,is_checked,set')->select();
            $setList = [];
            foreach ($set as $set_k=>$set_v){
                if(!empty($set_v['set'])){
                    $set_v['set'] = unserialize($set_v['set']);
                }
                $setList[$set_v['name']] = $set_v;
            }
            //数量价格格式化
            $number_decimal = $setList['number_decimal']['value'];
            $price_decimal  = $setList['price_decimal']['value'];

            $count = [
                'i_number'=>0,
                'unit_price'=>0,
                'all_money'=>0,
                'tax_money'=>0,
                'money_tax_price'=>0,
            ];
            $counts = $count;
            $counts['s_name'] = '合计';$counts['s_type'] = 3;
            $data = [];
            $now = isset($listarr[0][$field])?$listarr[0][$field]:'';
            foreach ($listarr as $list_k=>$list_v){
                if($list_v[$field]!=$now){
                    $now = $list_v[$field];
                    $row = $count;$row['s_name'] = '小计';$row['s_type'] = 2;
                    $row['unit_price'] = round($row['all_money']/$row['i_number'],2);
                    $data[] = $row;
                    foreach ($count as $count_k=>$count_v){
                        $count[$count_k] = $list_v[$count_k];
                        $counts[$count_k] += $list_v[$count_k];
                    }
                }else{
                    foreach ($count as $count_k=>$count_v){
                        $count[$count_k] += $list_v[$count_k];
                        $counts[$count_k] += $list_v[$count_k];
                    }
                }
                $data[] = $list_v;
                if($list_k==(sizeof($listarr)-1) || sizeof($listarr)==1){
                    $row = $count;$row['s_name'] = '小计';$row['s_type'] = 2;
                    if($row['i_number']!=0){
                        $row['unit_price'] = round($row['all_money']/$row['i_number'],$price_decimal);
                    }else{
                        $row['unit_price'] = 0;
                    }
                    $data[] = $row;
                }
            }
            $counts['unit_price'] = $counts['i_number']>0?(round($counts['all_money']/$counts['i_number'],$price_decimal)):0;

            $counts['i_number'] = round($counts['i_number'],$number_decimal);
            $counts['unit_price'] = round($counts['unit_price'],$price_decimal);
            $counts['all_money'] = round($counts['all_money'],$price_decimal);
            $counts['tax_money'] = round($counts['tax_money'],$price_decimal);
            $counts['money_tax_price'] = round($counts['money_tax_price'],$price_decimal);

            $result = array("count" => sizeof($data), "list" => $data,'sum'=>$counts);

            if(isset($result['list']) && isset($result['count'])){
                $this->success('查询成功',$result,200);
            }else{
                $this->error('查询失败','',406);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }
}
